<template>
  <base-modal
    :show.sync="visible"
    width="500px"
    class="editor-column-dialog"
    @closed="onClose('form')"
  >
    <div slot="title">
      <span class="el-dialog__title">{{ $t('task.setting.components.editFields') }}</span>
    </div>

    <div class="base-modal-content">
      <el-checkbox v-model="isCheckedAll" @change="toggle">{{ $t('common.base.selectAll') }}</el-checkbox>
      <el-checkbox-group v-model="checkedGroupArr" class="check-item-con">
        <el-checkbox v-for="col in filterColumns" :key="col.value" :label="col.value" @change="handleChangeGroup($event, col.value)">
          {{ col.label }}
        </el-checkbox>
      </el-checkbox-group>

      <div v-for="item in filterColumns" :key="item.value">
        <div class="check-item-title">{{ item.label }}</div>
        <el-checkbox-group v-model="checkedMap[item.value]" class="check-item-con">
          <el-checkbox 
            v-for="field in item.columns" 
            :key="field.fieldName" 
            :label="field.fieldName"
            :disabled="handleDisable(field)" 
            @change="handleCheckboxChildChange($event, item.value)">
            {{ field.displayName }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="onClose">{{ $t('common.base.cancel') }}</el-button>
      <el-button type="primary" @click="onSubmit">{{ $t('common.base.makeSure') }}</el-button>
    </div>
  </base-modal>
</template>
<script>
/* util */
import _ from 'lodash';
export default {
  name: 'editor-column-dialog',
  props: {
    // 编辑显示的fields
    fieldsOptions: {
      type: Array,
      default:() => ([])
    },
    // 编辑选中的数据
    editSelectedData: {
      type: Array,
      default:() => ([])
    }
  },
  data() {
    return {
      visible: false,
      isCheckedAll: false,
      checkedGroupArr: [],
      checkedMap: {
        systemChecked: [],
        customChecked: [],
      },
      filterColumnsExpandLength: 0, // 表单字段的总长度
      filterColumns: [], // 显示的字段
      filterColumnsMap: {},
      // 物料编号、物料名称、预计用量、申领数量、出库数量、小计 禁止点击 & 默认选中
      disableArr: ['serialNumber', 'name', 'preNum', 'usedNum', 'total', 'applyNum']
    };
  },
  computed: {
    // 选中的长度
    checkedLength() {
      let checkedMap = this.checkedMap;
      let length = 0;

      for (let key in checkedMap) {
        let columns = checkedMap[key];
        length += columns.length;
      }

      return length;
    }
  },
  methods: {
    handleCheckboxChildChange($event, value) {
      // 默认的group item的数组长度
      const defaultGroupItemLength = this.filterColumns.find(item => item.value === value)?.columns?.length || 0;
      // 选中group的长度
      const checkedGroupItemLength = this.checkedMap[value].length;
      // 需要删除的数组下标index
      const needSpliceIndex = this.checkedGroupArr.findIndex(item => item === value);
      // 根据相关选中的长度判断是否小于默认的group的长度判断去删除顶部选中的checkbox Item
      checkedGroupItemLength < defaultGroupItemLength ? needSpliceIndex > -1 && this.checkedGroupArr.splice(needSpliceIndex, 1) : this.checkedGroupArr.push(value);
      this.handleChange();
    },
    checkedAll(checkedAll = true) {
      let checkedMap = this.checkedMap;

      this.checkedGroupArr = [];

      for (let key in checkedMap) {
        let columns = this.filterColumnsMap[key] || [];

        let checkedArr = [];

        if (checkedAll) {
          checkedArr = columns?.map(item => item.fieldName);
          this.checkedGroupArr.push(key);
        } else {
          checkedArr = this.disableArr;
        }
        this.$set(this.checkedMap, key, checkedArr);
      }
    },
    // 全选
    toggle(value) {
      this.checkedAll(value);
    },
    handleChangeGroup($event, value) {
      let checkedArr = [];

      // 全部选中了系统字段或者自定义字段
      if(this.checkedGroupArr.includes(value)) {
        let columns = this.filterColumnsMap[value] || [];
        checkedArr = columns.map(item => item.fieldName);
      } else if (value === 'systemChecked') {
        checkedArr = this.disableArr;
      }

      this.$set(this.checkedMap, value, checkedArr);

      this.handleChange();
    },
    handleChange() {
      // 这里判断是否取消全选的checkbox
      this.isCheckedAll = this.checkedLength == this.filterColumnsExpandLength;
    },
    openDialog() {
      this.filterColumnsExpandLength = this.fieldsOptions.length;

      this.buildField();

      let systemChecked = []
      let customChecked = []

      this.editSelectedData.map(item => {
        if (!!item.isSystem) {
          systemChecked.push(item.fieldName)
        } else {
          customChecked.push(item.fieldName)
        }
      })

      // // el-checkbox js 修改checked绑定的值时，不会出发change事件，
      this.$set(this.checkedMap, 'systemChecked', systemChecked);
      // // 手动触发
      this.handleCheckboxChildChange('', 'systemChecked');

      this.$set(this.checkedMap, 'customChecked', customChecked);
      this.handleCheckboxChildChange('', 'customChecked');
      
      this.visible = true;
    },
    buildField() {
      const systemFields = {
        label: this.$t('common.form.fieldGroupName.system'),
        value: 'systemChecked',
        columns: this.fieldsOptions.filter(item => !!item.isSystem)
      }

      const customFields = {
        label: this.$t('common.form.fieldGroupName.attribute'),
        value: 'customChecked',
        columns: this.fieldsOptions.filter(item => !item.isSystem)
      }

      let column = [systemFields, customFields].filter(item => {
        return item.columns && item.columns.length > 0;
      });

      this.filterColumns = column;

      column.map(item => {
        this.filterColumnsMap[item.value] = item.columns;
      });
    },
    // 默认勾选 - disabled
    handleDisable(field) {
      if (this.disableArr.includes(field.fieldName)) {
        return true;
      } 
      return false;
    },
    onClose() {
      this.visible = false;
      this.filterColumnsExpandLength = 0;
      this.checkedGroupArr = [];
    },
    onSubmit() {
      this.onClose();

      let checkMap = [
        ...this.checkedMap.systemChecked,
        ...this.checkedMap.customChecked,
      ]

      let field = this.fieldsOptions;

      let selectField = field.filter(item => {
        return checkMap.includes(item.fieldName)
      })

      this.$emit('onSave', selectField);
    },
  },
};
</script>
<style lang="scss" scoped>
.editor-column-dialog {
  ::v-deep .base-modal-header {
    display: flex;
    justify-content: space-between;
    .el-dialog__title {
      font-size: 18px;
    }
    .el-tooltip {
      color: #999;
    }
  }
  ::v-deep .base-modal-body {
    padding: 20px;

    .check-item-title {
      margin: 14px 0 4px;
      font-weight: 500;
      font-size: 15px;
    }
    .check-item-con {
      display: flex;
      flex-flow: row wrap;
    }
  }

  ::v-deep .el-checkbox {
    margin-left: 0;
    min-width: 25%;
    width: auto;
  }
}
</style>